package br.com.mizzu.taglibs;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyTagSupport;

public class iterate extends BodyTagSupport {
	private static final long serialVersionUID = 1L;
	private String var;
	private List<Object> list;
	private int maxElements=-1;
	private int start=0;
	private int listSize;
	private int count=0;
	
	public void doInitBody() throws JspException {
		if(list == null){
			list = new ArrayList<Object>();
		}
		listSize = list.size();
		maxElements = (maxElements==-1) ? listSize : maxElements;
		count = start;
	}

	public int doAfterBody() throws JspException {
		if(count == listSize || count == maxElements + start){
			return SKIP_BODY;
		}else{
			pageContext.setAttribute(var, list.get(count));
			count++;
			return EVAL_BODY_AGAIN;
		}
	}

	public int doEndTag() throws JspException {
		try {  
			pageContext.getOut().print(bodyContent.getString());
			return EVAL_PAGE;
		} catch(IOException e) {
			throw new JspException(e.getMessage());
		} 
	}

	public List<Object> getList() {
		return list;
	}

	public void setList(List<Object> list) {
		this.list = list;
	}

	public String getVar() {
		return var;
	}

	public void setVar(String var) {
		this.var = var;
	}

	public int getMaxElements() {
		return maxElements;
	}

	public void setMaxElements(int maxElements) {
		this.maxElements = maxElements;
	}

	public int getStart() {
		return start;
	}

	public void setStart(int start) {
		this.start = start;
	}
}
